#!/usr/bin/env python
#coding=utf-8

import cgi
import wsgiref.handlers
import os
import logging
import datetime

from models import *
from utils import *
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.api import urlfetch
from google.appengine.api import users
from google.appengine.api import memcache
from django.template import TemplateSyntaxError

class BaseRequestHandler(webapp.RequestHandler):
	def __init__(self):
		pass

	def param(self, name, **kw):
		return self.request.get(name, **kw)

	def write(self, s):
		self.response.out.write(s)

	def error_404(self):
		logging.error(self.request.path_qs)
		self.response.set_status(404)
		self.template_values.update({
			'url' : self.request.uri,
			})
		self.render('templates/error_404_page.html')

	def initialize(self, request, response):
		webapp.RequestHandler.initialize(self, request, response)

		self.userInfo = UserInfo()
		login_user = users.get_current_user()
		if login_user != None:
			self.userInfo.user = login_user
			self.userInfo.isLogin = True

		self.userInfo.isAdmin = users.is_current_user_admin()
		self.userInfo.loginUrl = users.create_login_url(request.uri)
		self.userInfo.logoutUrl = users.create_logout_url(request.uri)

		try:
			self.referer = self.request.headers['referer']
		except:
			self.referer = None

		self.template_values = {
        'userInfo' : self.userInfo,
				'self' : self,
				}

	def render(self, templateName, html=None):
		if html == None:
			values = self.template_values
			#html = memcache.get('%s:page:%s' % (self.login_user, self.request.path_qs))

			if html == None:
				try:
					path = os.path.join(os.path.dirname(__file__), templateName)
					html = template.render(path, values)
				except TemplateSyntaxError, e: # if theme files are not found, fall back to default theme
					logging.error(e)
					self.redirect("/")
					return
				#memcache.set('%s:page:%s' % (self.login_user, self.request.path_qs), html)

		self.write(html)

# {{{ Not Found
class NotFound(BaseRequestHandler):
	def get(self):
		self.error_404()
# }}}